package db_guess

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	db_main2 "longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/mysql/models/models_main"
	"math"
	"time"

	"gorm.io/gorm"
)

/*
*
Enzo 2022 July19
插入一张竞猜订单
*/
func InsertGuessOrderByTx(gorder *models_guess.GuessOrder) (int, error) {
	fName := "InsertGuessOrder"
	return GuessInsertAny(gorder, fName)
}

func UserProcessGuessOrderByTx(gorder *models_guess.GuessOrder, session *gorm.DB,
	amount int, isProfit int, consumeType int) (int, error) {
	fName := "UserProfitGuessOrder"
	userProfit := &models_main.UserProfit{
		Uid:         gorder.Uid,      //投注的人
		FUid:        gorder.AnchorId, //主持人
		CoinCount:   amount,          //总价格
		Type:        isProfit,        //0 付款，1 得钱
		ConsumeType: consumeType,
		Resid:       gorder.GuessItem, //用户选了哪项
		Content: fmt.Sprintf("%s(主播ID:%d 竞猜ID:%d)游戏竞猜 %s%.2f%s",
			util.GetConsumeVerb(consumeType, isProfit),
			gorder.AnchorId,
			gorder.GuessId,
			util.GetConsumeNoun(consumeType),
			math.Abs(float64(amount))/100,
			util.GetCoinName(_const.FEE_TYPE_GOLD)),

		Count:      1,
		CreateTime: time.Now(),
		CoinType:   _const.FEE_TYPE_GOLD,

		OrderNo: util.GenOrderId("GU", 1),
		Liveid:  int64(gorder.LiveId),
	}

	id, err := mysql.InsertAnyByTx(session, userProfit, fName)
	if err != nil {
		global2.Log.Error("69%s主播收益记录写入失败:%v", fName, userProfit)
		return 0, err
	}
	return id, nil
}

func ProcessGuessOrder(gorder *models_guess.GuessOrder) (int, error) {
	//fName := "ProcessGuessOrder"
	session := global2.GetX().Begin()
	//加减钱
	_, _, err := db_main2.UpdateAmountByTx(gorder.Uid, -gorder.Amount, _const.CoinGold, session, _const.WALLET_BALANCE_HIDE, nil)
	if err != nil {
		global2.Log.Errorf("6ProcessGuessOrder9%v", err)
		return 0, err
	}
	id, err := UserProcessGuessOrderByTx(gorder, session, -gorder.Amount, 0, _const.CONSUME_GUESS)
	if err != nil {
		global2.Log.Errorf("6ProcessGuessOrder9%v", err)
		return 0, err
	}
	_, err = mysql.InsertAnyByTx(session, gorder, "ProcessGuessOrder")
	if err != nil {
		global2.Log.Errorf("6ProcessGuessOrder9%v", err)
	}
	//提交事务
	if err = session.Commit().Error; err != nil {
		session.Rollback()
		global2.Log.Errorf("6ProcessGuessOrder9%v", err)
		return 0, err
	}

	return id, nil
}

// 算奖，把所有订单和开奖结果比对一下，计算奖金，并把状态改为中奖未派奖；
func ProcessSettleOrder(gorder *models_guess.GuessOrder, guess *models_guess.Guess, iDelta int, consumeType int) (int, error) {
	var err error
	var iCode int
	gorder.UpdateTime = time.Now()
	if iDelta == 0 { //没有账变，散会
		if gorder.Status == _const.GUESS_ORDER_MISSED { //当没中奖时没有账变，但要改一下订单的状态
			iCode = 1
			err = mysql.UpdateXAnyParam(nil, []string{"status", "pay_status", "profit", "update_time"}, gorder, "settleMissedOrder")
		}
		return iCode, nil
	}
	var isProfit = 0
	if iDelta > 0 {
		isProfit = 1
	}
	if gorder.Status == _const.GUESS_ORDER_WIN {
		consumeType = _const.PROFIT_GUESS_WIN
	} else if gorder.Status == _const.GUESS_ORDER_MISSED {

	} else if gorder.Status == _const.GUESS_STATUS_SETTLED_CANCELED { // 派奖后取消
		if iDelta > 0 {
			consumeType = _const.PROFIT_GUESS_RETURN //加钱
		} else {
			consumeType = _const.CONSUME_GUESS_CANCEL_WIN //减钱
		}
	}
	fName := "6ProcessSettleOrder9"
	session := global2.GetX().Begin()
	//加减钱
	_, _, err = db_main2.UpdateAmountByTx(gorder.Uid, iDelta, _const.CoinGold, session, _const.WALLET_BALANCE_HIDE, nil)
	if err != nil {
		global2.Log.Errorf("%s%v", fName, err)
		return 0, err
	}
	id, err := UserProcessGuessOrderByTx(gorder, session, iDelta, isProfit, consumeType)
	if err != nil {
		session.Rollback()
		global2.Log.Errorf("%s%v", fName, err)
		return 0, err
	}
	//update order

	err = mysql.UpdateXAnyParam(session, []string{"update_time", "status", "pay_status", "profit", "odds"},
		gorder, "6ProcessSettleOrder9")
	if err != nil {
		session.Rollback()
		global2.Log.Errorf("%s%v", fName, err)
		return 0, err
	}
	//提交事务
	if err = session.Commit().Error; err != nil {
		global2.Log.Errorf("%s%v", fName, err)
		return 0, err
	}
	return id, nil
}
func CalcContinueWin(uid int) int64 {
	lastLoss := &models_guess.GuessOrder{}
	iLastId := 0
	var n int64
	_ = mysql.GetXAnyParam(lastLoss, map[string]interface{}{"status": _const.GUESS_ORDER_MISSED, "uid": uid}, true, "CalcContinueWin")
	iLastId = lastLoss.Id
	global2.Log.Debugf("count lastId: %+v", lastLoss)
	err := mysql.CountXAnyParam(&models_guess.GuessOrder{}, &n, map[string]interface{}{
		"status": _const.GUESS_ORDER_WIN,
		"uid":    uid,
		"id":     map[string]interface{}{">": iLastId}}, //时间晚于最后一次输的，然后状态是赢的
		"CalcContinueWin", "id desc", "guess_id", 0, 0) //以guess_id去重
	global2.Log.Debugf("count result: %d", n)
	if err != nil {
		n = 0
	}
	return n
}
